import $ from 'jquery';
import Vue from 'vue';
import {Modal} from 'ant-design-vue';
import {getFieldComponent} from '@/components/hhd/design/FormDesigner/field/comps/FieldRegister';

export function getElementParentUntilHasRole(el, role) {
  while (el && $(el).attr('data-role') !== role) el = el.parentNode;
  return el;
}

export function getElementParentUntilTag(el, tagName) {
  while (el && el.tagName !== tagName.toUpperCase()) el = el.parentNode;
  return el;
}

export function isRole(el, role) {
  return $(el).attr('data-role') === role;
}

export function createDraginRootPlaceholder() {
  let div = document.createElement('div');
  div.className = 'dragin-root-placeholder';
  $(div).attr('data-role', 'placeholder');
  // div.innerHTML = '放在这里';
  return div;
}

export function createDefaultFieldElement() {
  let div = document.createElement('div');
  $(div).addClass('field-component');
  return div;
}

export function createButton(config) {
  let div = document.createElement('div');
  $(div).addClass('ant-btn design-button');
  let icon = $(`<span class="iconfont design-button-icon">${config.icon && ('&#' + config.icon + ';') || ''}</span>`);
  let label = $(`<span class="design-button-label">${config.buttonName}</span>`);
  $(div).append(icon);
  $(div).append(label);
  return div;
}

export function clearPlaceholder(placeholder) {
  $(placeholder).remove();
}

export function stop(e) {
  e.stopPropagation();
  e.preventDefault();
}

export function createFieldBarWrapper() {
  let div = document.createElement('div');
  $(div).addClass('field-bar-container');
  let deleteButton = $(`<span data-action="removeField" data-role="drag-bar-action" class="iconfont border-icon">&#xe620;</span>`);
  $(div).append(deleteButton);
  return div;
}

export function getBarAction(bar) {
  return $(bar).attr('data-action');
}

const VueProperties = {
  h: undefined
};

export function openModal(vnode, config) {
  let div = document.createElement('div');
  document.body.appendChild(div);
  let app = new Vue({
    data() {
      return {
        visible: true
      };
    },
    mounted() {
      this.$nextTick(() => config.mounted && config.mounted());
    },
    render() {
      return VueProperties.h(Modal, {
        ref: 'modal',
        props: {
          ...config,
          visible: this.visible,
          okText: '确定',
          cancelText: '取消'
        },
        on: {
          ok() {
            config.ok && config.ok(app);
          },
          cancel() {
            config.cancel && config.cancel(app) || app.close();
          },
        }
      }, [vnode]);
    },
    methods: {
      close() {
        this.visible = false;
        setTimeout(() => {
          $(app.$el).parent().remove();
          $(div).remove();
        }, 300);
      },
    }
  });
  app.$mount(div);
}

export {VueProperties};

export function createLayoutBarContainer() {
  let div = document.createElement('div');
  $(div).addClass('layout-bar-container');
  $(div).append(createLayoutBarButton({icon: '&#xe83d;', action: 'move'}));
  $(div).append(createLayoutBarButton({icon: '&#xe80e;', action: 'resolveLayoutWidth'}));
  $(div).append(createLayoutBarButton({icon: '&#xe620;', action: 'removeLayout'}));
  return div;
}

function createLayoutBarButton({icon, action}) {
  let span = document.createElement('span');
  $(span).addClass('iconfont');
  $(span).attr('data-role', 'drag-bar-action');
  $(span).attr('data-action', action);
  $(span).addClass('layout-bar-button');
  $(span).html(icon);
  return span;
}

export function setSelectFieldStyle(el) {
  $('.select-field').removeClass('select-field');
  $(el).addClass('select-field');
}

export function getFieldId(el) {
  return $(el).attr('data-field-id');
}

export function isEmptyContent(el) {
  let contentWrapper = $(el).find('.content-wrapper')[0];
  if (contentWrapper && contentWrapper.textContent) {
    return false;
  }
  if ($(contentWrapper).children().length !== 0) {
    return false;
  }
  if ($(el).find('[data-role=field]').length !== 0) {
    return false;
  }
  return true;
}

export function isSubTable(el) {
  return $(el).attr('data-layout-type') === 'subTable';
}

export function getSubTableRole(el) {
  return $(el).attr('data-sub-table-role');
}

export function getSubTableId(el) {
  return $(el).attr('data-sub-form-id');
}

export function getFieldConfigById(id, formDefinition) {
  if (!id || !formDefinition) return null;
  let fields = formDefinition && formDefinition.fields || [];
  let res = fields.find(f => f.id === id);
  if (res) return res;
  let subForms = formDefinition && formDefinition.subForms || [];
  subForms.forEach(subform => {
    fields = subform && subform.fields || [];
    res = res || fields.find(f => f.id === id);
  });
  let views = formDefinition && formDefinition.views || [];
  views.forEach(v => {
    let components = v && v.components || [];
    res = res || components.find(c => c.id === id);
  });
  return res;
}

export function isMainField(fieldId, formDefinition) {
  let field = (formDefinition && formDefinition.fields || []).find(f => f.id === fieldId);
  return !!field;
}

export function isSubFormField(fieldId, formDefinition) {
  let field = undefined;
  (formDefinition && formDefinition.subForms || []).forEach(f => {
    (f && f.fields || []).forEach(f => {
      if (f.id === fieldId) field = f;
    });
  });
  return !!field;
}

export function isSubTableBody(tr) {
  return $(tr).attr('data-sub-table-role') === 'body';
}

export function isSubTableHeader(tr) {
  return $(tr).attr('data-sub-table-role') === 'header';
}

export function isSubTableFooter(tr) {
  return $(tr).attr('data-sub-table-role') === 'footer';
}

export function getSubFormIdByFieldId(fieldId, formDefinition) {
  let res = undefined;
  (formDefinition && formDefinition.subForms || []).forEach(subForm => {
    (subForm && subForm.fields || []).forEach(f => {
      if (f.id === fieldId) {
        res = subForm.id;
      }
    });
  });
  return res;
}

export function getSubFormIdByLayoutElement(el) {
  return $(el).attr('data-sub-form-id');
}

export function getSubFormById(id, formDefinition) {
  return (formDefinition && formDefinition.subForms || []).find(subForm => subForm.id === id);
}

export function canDragin(el, fieldId, formDefinition) {
  let layout = getElementParentUntilHasRole(el, 'layout');
  let tr = getElementParentUntilTag(el, 'tr');
  if (isMainField(fieldId, formDefinition)) {
    //当前拖拽的是一个主表字段
    if (isSubTable(layout)) {
      //如果主表字段拖拽到了明细表的header或者footer上面, 返回true,
      //否则返回false
      return isSubTableHeader(tr) || isSubTableFooter(tr);
    }
  }
  if (isSubFormField(fieldId, formDefinition)) {
    if (!isSubTable(layout)) return false;
    let subFormId1 = getSubFormIdByFieldId(fieldId, formDefinition);
    let subFormId2 = getSubFormIdByLayoutElement(layout);
    //当前拖拽的是一个明细表字段
    if ((subFormId1 === subFormId2) && isSubTableBody(tr)) {
      return true;
    }
    return false;
  }
  return true;
}

export function createSubTableByConfig(subForm, callback) {
  try {
    let fields = subForm.fields || [];
    if (!fields || !fields.length) {
      callback();
      return;
    }
    let table = getFieldComponent('subTable').comp.createSubTableElementByConfig({
      row: 3,
      col: subForm.fields.length + 1
    });
    table = createFieldWrapper(table);
    $(table).attr('data-layout-type', 'subTable');
    $(table).attr('data-role', 'layout');
    $(table).attr('data-sub-form-id', subForm.id);
    $(table).append(createLayoutBarContainer());

    let tds = $(table).find('tr[data-sub-table-role=body]').find('td');
    let count = 0;
    for (let i = 0; i < fields.length; i++) {
      let fieldConfig = fields[i];
      let fieldComponent = getFieldComponent(fieldConfig.component);
      fieldComponent.comp.createField().then(({el}) => {
        $(el).attr('data-role', 'field');
        $(el).attr('data-field-id', fieldConfig.id);
        $(el).attr('draggable', true);
        $(el).append(createFieldBarWrapper());
        $(tds[i + 1]).append(el);
        if (++count === fields.length) {
          callback(table);
        }
      });
    }
    return;
  } catch (e) {
    console.error(e);
  }
  callback(null);
}

export function getFieldIndex(index) {
  index += '';
  while (index.length < 5) {
    index = '0' + index;
  }
  return index;
}

export function createFieldWrapper(el) {
  let div = document.createElement('div');
  $(div).append(el);
  $(div).addClass('field-wrapper');
  // $(div).addClass('field-component');
  return div;
  // return el;
}

export function getSubFormByFieldId(id, formDefinition) {
  let subForms = formDefinition.subForms || [];
  for (let i = 0; i < subForms.length; i++) {
    let subForm = subForms[i], fields = subForm.fields || [];

    for (let j = 0; j < fields.length; j++) {
      if (fields[j].id === id) {
        return subForm;
      }
    }
  }
}

export function createFieldIndexString(index) {
  let res = index + '';
  while (res.length < 5) res = '0' + res;
  return res;
}


const dragShadowImgData = {
  wrapper: undefined,
  startX: 0,
  startY: 0,
  left: 0,
  top: 0,
};

export function startDragShadowImg(e, dragging) {
  e = e.originalEvent || e;
  if (!e.dataTransfer) return;
  e.dataTransfer.setDragImage(document.createElement('div'), 0, 0);
  let container = $(dragging).parent();
  let rect = dragging.getBoundingClientRect();
  dragging = $(dragging).clone();
  let wrapper = document.createElement('div');
  $(wrapper).addClass('dragging-shadow-img');
  $(wrapper).width(rect.width);
  $(wrapper).height(rect.height);
  $(wrapper).css('left', `${rect.x}px`);
  $(wrapper).css('top', `${rect.y}px`);
  $(wrapper).append(dragging);
  $(container).append(wrapper);
  $(wrapper).find('.is-moving').removeClass('is-moving');

  dragShadowImgData.wrapper = wrapper;
  dragShadowImgData.startY = e.clientY;
  dragShadowImgData.startX = e.clientX;

  dragShadowImgData.left = rect.x;
  dragShadowImgData.top = rect.y;
}

export function stopDragShadowImg() {
  $(dragShadowImgData.wrapper).remove();
}

export function dragShadowImgMousemove(e) {
  e = e.originalEvent || e;
  $(dragShadowImgData.wrapper).css('left', `${dragShadowImgData.left + e.clientX - dragShadowImgData.startX}px`);
  $(dragShadowImgData.wrapper).css('top', `${dragShadowImgData.top + e.clientY - dragShadowImgData.startY}px`);
}

export function createSubFormButton(icon, label, type) {
  return `<button type="button" class="ant-btn ant-btn-${type} ant-btn-round sub-form-action-button">
    <span class="iconfont anticon">${icon}</span>
    <span>${label}</span>
  </button>`
}